/**
 * 
 */
package edu.gtcfla.km.admin.appmodules.web;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.shiro.authz.annotation.RequiresUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.vsg.biz.BusinessOperationException;
import org.vsg.common.i18n.I18nMessageService;
import org.vsg.common.web.json.SubmitResult;
import org.vsg.common.web.json.processor.JsDateViewJsonValueProcessor;
import org.vsg.security.annotation.RegisterRequestPermissionStrategy;

import edu.gtcfla.km.admin.appmodules.service.MenuManagerService;
import edu.gtcfla.km.admin.appmodules.service.MenuResourceService;
import edu.gtcfla.km.admin.appmodules.vo.HierarchyMenuItem;
import edu.gtcfla.km.admin.appmodules.vo.HierarchyMenuResourcePermissionVO;
import edu.gtcfla.km.admin.appmodules.vo.MenuFormView;
import edu.gtcfla.km.admin.appmodules.vo.MenuWithMethodVO;
import edu.gtcfla.km.core.ApplicationConstant;

/**
 * @author Bill vison
 *
 */
@Controller
@Lazy
@RequestMapping(ApplicationConstant.DATA_RERESOURCE)
public class MenuResController {
	
	private final static Logger logger = LoggerFactory.getLogger(MenuResController.class);	

	
	private final String modulePrefix = "/resources";

	
	@Autowired(required =false)
	private MenuManagerService  menuResourceManagerService;
	
	@Autowired(required =false)
	private MenuResourceService menuResourceService;
	
	
	@Autowired(required =false)
	private I18nMessageService i18nMessageService;	
	

	
	@RequiresUser
	@RegisterRequestPermissionStrategy(
		value = "/resources/menu/alltrees.json",
		skipCheck = true
	)
	@RequestMapping(value = modulePrefix + "/menu/alltrees.json")
	public @ResponseBody Set<HierarchyMenuItem> accessAllmenus()
			throws Exception {

		Set<HierarchyMenuItem> hierachyMenResviews = menuResourceManagerService.buildHierachyMenuResourceView();
        
		return hierachyMenResviews;

	}

	@RequiresUser
	@RegisterRequestPermissionStrategy(
		value = "mergeAllMenu.json",
		skipCheck = true
	)	
	@RequestMapping(value = ApplicationConstant.DATA_RERESOURCE + "/mergeAllMenu.json")
	public ModelAndView accessOfMergeAllMenu(String jsonData)
			throws Exception {

		// --- map to json object data ---
		SubmitResult result = new SubmitResult();
		if (jsonData == null ) {
			result.setSuccess( false );
			String msg = i18nMessageService.getMessage("crm.module-admin.mergemenu.error", null);
			result.setMsg(msg);					
		} else {

			JSONArray jsonArray = JSONArray.fromObject( jsonData );			
			
			@SuppressWarnings("unchecked")
			ListIterator<JSONObject> li = (ListIterator<JSONObject>) jsonArray.listIterator();
			
			Set<MenuWithMethodVO> menuMethodSet = new LinkedHashSet<MenuWithMethodVO>();
			MenuWithMethodVO menusMethod = null;
			while ( li.hasNext() ) {
				JSONObject obj = li.next();
				
				menusMethod = new MenuWithMethodVO();

				String method = obj.getString("method");
				menusMethod.setMethod( method );
				menusMethod.setMenuId( obj.getString("id") );

				// --- update record ---
				if (method.equals("update")) {
					String menuCode = obj.getString("code") ;
					String parentId = obj.getString("parentId");
					
					menusMethod.setMenuCode(menuCode);
					menusMethod.setParentId(parentId);
				}
				
				menuMethodSet.add( menusMethod );
			}
			
			
			menuResourceManagerService.mergeAllMenuMethod( menuMethodSet );

			result.setSuccess(true);
			String msg = i18nMessageService.getMessage("crm.module-admin.mergemenu.success", null);
			result.setMsg(msg);
			
		}

		
		JsonConfig jcfg = new JsonConfig();	
		jcfg.registerJsonValueProcessor(java.util.Date.class,new JsDateViewJsonValueProcessor());
		JSONObject jsonObject = JSONObject.fromObject(result, jcfg);		
		
		// --- reflesh ----

		ModelAndView mav = new ModelAndView();
		mav.addObject("json", jsonObject);
		mav.setViewName("result"); // view name

        
		return mav;

	}
	


	@RequiresUser
	@RegisterRequestPermissionStrategy(value = modulePrefix + "/menu/update_all.json", skipCheck = true)
	@RequestMapping(value = modulePrefix	+ "/menu/update_all.json")
	public @ResponseBody SubmitResult accessUpdateMenus(@RequestBody List<Map<String,Object>> receiveValues)
			throws Exception {


		Set<MenuFormView> resPerms = new LinkedHashSet<MenuFormView>();
		
		for (Map<String,Object> item : receiveValues) {
			
			Boolean disabled = (Boolean)item.get("disabled");
			
			Integer sortNum = (Integer)item.get("sortNum");
			
			MenuFormView menuVO = new  MenuFormView(); 
			menuVO.setId( (String)item.get("id"));
			menuVO.setName( (String) item.get("text"));
			menuVO.setParentId( (String)item.get("parentId") );
			if (disabled) {
				menuVO.setDisabled( (short)1 );
			}
			
			if ( sortNum != null ) {
				menuVO.setSortNum( sortNum.shortValue());
			}
			  
			resPerms.add(menuVO);
		}
		
		// --- remove user id ---

		SubmitResult result = new SubmitResult();
		try {

			menuResourceService.updateAll(resPerms);

			result.setSuccess(true);
			String msg = i18nMessageService.getMessage(
					"module-admin.menu.update.success", null);
			result.setMsg(msg);

		} catch (Exception se) {
			// TODO Auto-generated catch block
			se.printStackTrace();
			result.setSuccess(false);
			String msg = i18nMessageService.getMessage(
					"module-admin.menu.update.error", null);
			result.setMsg(msg);
		}



		return result;
	}	
	
	@RequiresUser
	@RegisterRequestPermissionStrategy(
		value = modulePrefix + "/menu/allseltrees.json",
		skipCheck = true
	)		
	@RequestMapping(value = modulePrefix + "/menu/allseltrees.json")
	public  @ResponseBody Set<HierarchyMenuItem> accessAllSelectedTrees()
			throws Exception {

		Set<HierarchyMenuItem> hierachyMenResviews = this.menuResourceManagerService.selAllMenuTreeNode();
        
		return hierachyMenResviews;

	}
	
	@RequiresUser
	@RegisterRequestPermissionStrategy(
		value = modulePrefix + "/menu/submit_adding.json",
		skipCheck = true
	)	
	@RequestMapping(value = modulePrefix + "/menu/submit_adding.json")
	public SubmitResult submitAddMenuForm(MenuFormView accessForm)
			throws Exception {
		
		// --- save new menu ---
		SubmitResult submitRes = new SubmitResult();
		try {
			
			this.menuResourceManagerService.saveNewMenuFromView(accessForm);
			submitRes.setSuccess(true);
			
			String msg = i18nMessageService.getMessage("crm.module-admin.menu.save.success", null);
			submitRes.setMsg( msg); 

		} catch (BusinessOperationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
        
		return submitRes;

	}	
	
	@RequiresUser
	@RegisterRequestPermissionStrategy(
		value = "menulist_auth.json",
		skipCheck = true
	)		
	@RequestMapping(value = ApplicationConstant.DATA_RERESOURCE +"/menulist_auth.json")
	public ModelAndView accessOfMenuListAuth(String roleId)
			throws Exception {
		
		Set<HierarchyMenuResourcePermissionVO> permissionMenuResVOSet = new LinkedHashSet<HierarchyMenuResourcePermissionVO>();
		if (roleId == null || roleId.equals("")) {
			logger.info("prameter roleid is " + roleId);
		} else {
			// --- find all module ---
			permissionMenuResVOSet =  this.menuResourceManagerService.buildHierachyMenuPermissionByRoleId(roleId);
			
		}
		
		JsonConfig jcfg = new JsonConfig();	
		jcfg.registerJsonValueProcessor(java.util.Date.class,new JsDateViewJsonValueProcessor());
		JSONArray jsonObject = JSONArray.fromObject(permissionMenuResVOSet, jcfg);		

		
		System.out.println(jsonObject);
		ModelAndView mav = new ModelAndView();
		mav.addObject("json", jsonObject);
		mav.setViewName("result"); // view name
        
		return mav;

	}	
	
	@RequiresUser
	@RegisterRequestPermissionStrategy(value = modulePrefix + "/menu/submit_deleteall.json", skipCheck = true)
	@RequestMapping(value = modulePrefix	+ "/menu/submit_deleteall.json")
	public @ResponseBody SubmitResult accessDeleteMenus(@RequestBody List<String> receiveValues)
			throws Exception {


		
		// --- remove user id ---

		SubmitResult result = new SubmitResult();
		try {

			menuResourceService.deleteAll(new LinkedHashSet<String>( receiveValues ));

			result.setSuccess(true);
			String msg = i18nMessageService.getMessage(
					"module-admin.menu.update.success", null);
			result.setMsg(msg);

		} catch (Exception se) {
			// TODO Auto-generated catch block
			se.printStackTrace();
			result.setSuccess(false);
			String msg = i18nMessageService.getMessage(
					"module-admin.menu.update.error", null);
			result.setMsg(msg);
		}



		return result;
	}		
}
